var ListPageManager = ListPageManager || {};


var TABLE_DEF_SETTINGS = {
    // 是否允许检索
    "searching": false,
    // 是否允许排序
    "ordering": false,
    // 服务端
    "serverSide":true,
    // 是否表示 "processing" 加载中的信息，这个信息可以修改
    "processing": true,
    // 自动列宽
    "autoWidth":true,
    // 每次创建是否销毁以前的DataTable,默认false
    "destroy": false,
    // 重画时是否保持状态
    "stateSave":false,
    // 是否显示行数选择
    "lengthChange": false,
    // 每页的初期件数 用户可以操作lengthMenu上的值覆盖
    "pageLength": 10,
    // 水平滚动条
    "scrollX": false,
    // 垂直滚动条
    "scrollY": false,
    //翻页按钮样式
    // numbers:数字
    // simple:前一页，后一页
    // simple_numbers:前一页，后一页，数字
    // full:第一页，前一页，后一页，最后页
    //full_numbers:第一页，前一页，后一页，最后页，数字
    //first_last_numbers:第一页，最后页，数字
    "pagingType": "full_numbers",
    // 具体参考：https://datatables.net/reference/option/dom
    "dom": "Blfrt<clear><'row'<'col-sm-10'p>>",
    //dom: 'B<lf<t><p>',
    "language": {
        "processing": "数据正在加载中，请耐心等候！",
        "lengthMenu": "每页 _MENU_ 条记录",
        "zeroRecords": "没有找到记录",
        "info": "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
        "infoEmpty": "无记录",
        "infoFiltered": "(共 _MAX_条数据 )",
        "paginate": {
            "first":      "首页",
            "last":       "尾页",
            "next":       "下一页",
            "previous":   "上一页"
        }
    },
    /*
    	{
			"text":"添加",
			"action":function(e, dt, node, config){

			}
		}
    */
    "buttons": [],
    /*
    	ajax:{
			url:访问的链接地址
			dataSrc:返回的数据字段ps:{list:[{},{}]}值为list
			data:function(d){return d} //参数信息
    	}
    */
    "ajax":{
        dataSrc:'list'
    },
    /**
     columns:[
     {
         render://显示方法
         title:""//标题
         data: //数据
         "orderable":false,
         ""
     }
     ]
     */
    "columns":[],
    /*
      行创建成功
    */
    "createdRow":function(row,data,index){

    },
    /*
	  初期化成功
    */
    "initComplete":function(settings, json){

    },
    //绘画成功回调
    "drawCallback": function( settings ) {

    }
}

var TOOL_DT_DEF_SETTING = {
    "ajaxParam":function(){},
    "buttons":[],
    "addUrl":function(){return "";},
    "updUrl":function(row,data,index){return "";},
    "deleteUrl":function(row,data,index){return "";},
    ajax:{dataSrc:"list"},
    "tableInitComplete":function(settings, json){},
    "rowCreatedCall":function(row,data,index){},
    tableDrawedCall:function(settings){}
};

ListPageManager.DataTable = {
    /*
        settings:{
            // 是否允许检索
            "searching": false,
            // 是否允许排序
            "ordering": false,
            // 是否表示 "processing" 加载中的信息，这个信息可以修改
            "processing": true,
            // 自动列宽
            "autoWidth":true,
            // 每次创建是否销毁以前的DataTable,默认false
            "destroy": false,
            // 重画时是否保持状态
            "stateSave":false,
            // 是否显示行数选择
            "lengthChange": false,
            // 每页的初期件数 用户可以操作lengthMenu上的值覆盖
            "pageLength": 10,
            // 水平滚动条
            "scrollX": false,
            // 垂直滚动条
            "scrollY": false,
            deflist:true,
            "addUrl":function(){return "";}, //获得添加链接url
            "updUrl":function(data){return "";}, //获得更新链接url
            "deleteUrl":function(data){return "";}, //获得删除链接url
            ajax:{
                url:访问的链接地址
                dataSrc:返回的数据字段ps:{list:[{},{}]}值为list
                data:function(d){return d} //参数信息
            },
            buttons:[
                {cmd:"add"}, //默认命令
                {cmd:"del“,text:"删除",action:function(cmd,e, dt, node, config,tgoBj){
                        //cmd：动作命令,
                            e：事件类型,
                            dt：datatables对象,
                            node:对应的节点,
                            config：配置,
                            tgObj:tableManager对象【有checkbox的场景时,checkIds：代表所选择的checkBox的id】
                }}

                }
            ],
            withCheckColumn:{flg:false,key:"",idx:0}, //设置有checkbox,flg:true 时出现checkbox，key:代表需要使用的id,idx:表示checkBox的位置
            "columns":[
                    {
                        data:"", //数据
                        title:"", //标题
                        render:function(){

                        },
                        visible:true,
                        orderable:false,
                        searchable:false,
                        toolcolinfo:[
                                   {cmd:'udp',text:'更新',click:function(){}//不设置的话就使用默认的 },//默认命令
                                   {cmd:'del',text:'删除',click:function(){}//不设置的话就使用默认的 },//默认命令
                                   {cmd:'cmd',text:'',gettext:function(){},click:function(){}}//自定义的
                                 ]

                    }
             ],

             tableInitComplete:function(settings, json){ //表格初期化完成后调用

             }
             rowCreatedCall:function(row,data,index){ // 行创建成功后调用

             },
             tableDrawedCall:function(settings){ // 表格绘画完成后调用

             }

        }
    */
    init:function(settings,container){
        var _this = this;
        if(!container){return;}
        var parentContainr = $(container).parent();
        _this.toolObj = _this.tools();
        _this.settings = {};
        $.extend(_this.settings, TOOL_DT_DEF_SETTING, settings);
        var config = _this.toolObj.toTbSetting(_this.settings);
        _this.table = $(container).DataTable(config);
        _this.bindEvents(parentContainr,settings);
        _this.parent = parentContainr;
        return _this;
    },
    bindEvents:function(container,settings){
        if(settings){
            if(settings.withCheckColumn){
                if(settings.withCheckColumn.flg){
                    var allCheck = $(container).find(".all_check_select");
                    $(container).find(":checkbox.all_check_select").on("click",function () {
                        var flg = $(this).prop("checked");
                        $(container).find(".check_select").each(function () {
                            $(this).prop("checked",flg);
                        })
                    });
                }
            }
        }
    },
    getCheckInfo:function(settings){
        var _this = this;
        _this.checkIds = [];
        if(settings.withCheckColumn) {
            if (settings.withCheckColumn.flg) {

                _this.parent.find(".check_select").each(function () {
                    if($(this).prop("checked")){
                        _this.checkIds.push($(this).val());
                    }
                });
            }
        }
        return _this.checkIds;
    },
    redraw:function(){
        var _this = this;
        _this.table.draw();
    },
    tools:function(){
        var _this = this;
        return {
            toTbSetting:function(csettings){
                var config = {};
                for(var key in csettings){
                    if(!TOOL_DT_DEF_SETTING.hasOwnProperty(key)){
                        config[key] = csettings[key];
                    }
                }
                config.buttons = [];
                if(csettings.buttons && csettings.buttons.length > 0){
                    $(csettings.buttons).each(function(){
                        var cur = this;
                        var buttonObj = {};
                        // 添加按钮
                        if(this.cmd == "add"){
                            buttonObj.text = this.text || '添加';
                            if(this.action){
                                buttonObj.action = function(e, dt, node, config){
                                    cur.action.call(null,"add",e,dt,node,config);
                                }
                            }else{
                                buttonObj.action = function(e, dt, node, config){
                                    if(csettings.addUrl){
                                        var addUrlString = csettings.addUrl.call(null,e, dt, node, config,_this);
                                        ListPageManager.Popup.popFullPage(addUrlString,'新增',function(){
                                            _this.redraw();
                                        });
                                    }
                                }
                            }
                        }
                        else{
                            buttonObj.text = this.text || '按钮';
                            buttonObj.action = function(e, dt, node, config){
                                _this.getCheckInfo(csettings);
                                cur.action?cur.action.call(null,cur.cmd,e,dt,node,config,_this):void(0);
                            }
                        }
                        config.buttons.push(buttonObj);
                    });
                }
                // ajax
                config.ajax = {dataSrc:"list"};
                $.extend(config.ajax, csettings.ajax);
                if(csettings.ajaxParam){
                    config.ajax.data = function(d){
                        d["conditionVo"] = csettings.ajaxParam.call();
                        return {"condition":JSON.stringify(d)};
                    }
                }
                // columns
                config.columns =[];
                $.extend(config.columns, csettings.columns);
                if(csettings.withCheckColumn){
                    if(csettings.withCheckColumn.flg){
                        var idx = csettings.withCheckColumn.idx || 0;
                        config.columns.splice(idx,0,{"title":"<input type='checkbox' class='all_check_select'/>",render:function(data,type,row){
                                var key = csettings.withCheckColumn.key || "id";
                                return "<input type='checkbox' class='check_select' value='" + row[key] + "' />";
                            }
                        });
                    }
                }
                var columnBtns;
                $(config.columns).each(function(idx){
                    this.orderable=false;
                    this.searchable=false;
                    if(this.toolcolinfo){
                        this.data = "";
                        columnBtns = this.toolcolinfo;
                        this.render = function(data,type,row){
                            var html = "<div class='btn-group' >";
                            $(columnBtns).each(function(){
                                if(this.cmd=="upd"){
                                    this.text = this.text || "更新";
                                }
                                else if(this.cmd =="del"){
                                    this.text = this.text || "删除";
                                }
                                else if(this.gettext){
                                    this.text = this.gettext.call(null,data,type,row);
								}else{
                                    this.text = this.text || "按钮";
								}
                                html +=  "<button class='btn btn-primary' tg='" + this.cmd + "' type='button'>" + this.text + "</button>";
                            });
                            html += "</div>";
                            return html;
                        }
                    }else if(this.numbercol){
                        this.data = null;
                        _this.numberColIdx = idx;
                        config["fnDrawCallback"] = function () {
                            var api = this.api();
                            var startIndex = api.context[0]._iDisplayStart;
                            api.column(_this.numberColIdx).nodes().each(function(cell, i) {
                                cell.innerHTML =  startIndex + i + 1;
                            });
                        }
                    }
                });

                // tableInitComplete
                if(csettings.tableInitComplete){
                    config.initComplete = function(settings, json){
                        csettings.tableInitComplete.call(null, settings, json);
                    }
                }
                config.createdRow = function( row, data, dataIndex){
                    if(columnBtns && columnBtns.length > 0){
                        $(row).find(".btn").on("click",function(){
                            if($(this).attr("tg") == "upd"){
                                if(csettings.updUrl){
                                    var updUrlSetting = csettings.updUrl.call(null,row,data,dataIndex);
                                    ListPageManager.Popup.popFullPage(updUrlSetting,'修改',function(){
                                        _this.redraw();
                                    });
                                }
                            }
                            else if($(this).attr("tg") == "del"){
                                if(csettings.deleteUrl){
                                    var deleteUrl = csettings.deleteUrl.call(null,row,data,dataIndex);
                                    ListPageManager.Popup.confirm("确定要删除数据吗？",{},function(){
                                        $.ajax({
                                            url:deleteUrl,
                                            type:"get",
                                            success:function(res){
                                                if(res.success){
                                                    ListPageManager.Popup.msg(res.message,{},function(){
                                                        _this.redraw();
                                                    });
                                                }else{
                                                    ListPageManager.Popup.msg(res.message);
                                                }
                                            }
                                        })
                                    });
                                }
                            }
                            else{
                                var cmd = $(this).attr("tg");
                                $(columnBtns).each(function(){
                                    if(this.cmd == cmd){
                                        this.click?this.click.call(null,cmd,row,data,dataIndex):void(0);
                                    }
                                });
                            }
                        });
                    }
                    if(csettings.rowCreatedCall){
                        csettings.rowCreatedCall.call(null, row, data, dataIndex);
                    }
                }
                if(csettings.tableDrawedCall){
                    config.drawCallback = function(settings){
                        csettings.tableDrawedCall.call(null, settings);
                    }
                }
                config = $.extend({}, TABLE_DEF_SETTINGS, config);
                return config;
            }
        }
    }
};

ListPageManager.Tools = (function(){
    return {
        formatDate:function (timeStamp) {
            if(!timeStamp || timeStamp == ""){
                return "-";
            }
            function zeroBu(n){
                if(n<10){
                    return '0'+n;
                }else{
                    return n
                }
            }
            var time = new Date(timeStamp);
            var y = zeroBu(time.getFullYear());//年
            var m = zeroBu(time.getMonth() + 1);//月
            var d = zeroBu(time.getDate());//日
            var h =zeroBu( time.getHours());//时
            var mm =zeroBu( time.getMinutes());//分
            var s = zeroBu(time.getSeconds());//秒
            var times=y+"-"+m+"-"+d+" "+h+":"+mm+":"+s;
            return times;
        },
        ajax:function (option) {
            var idx;
            option.beforeSend = option.beforeSend || function(){
                idx = ListPageManager.Popup.loading();
            };
            option.complete = option.complete || function () {
                layer.close(idx);
            }
            $.ajax(option);
        },
        urlParam:function (url, param) {
            var pattern = new RegExp("[?&]" + param + "\=([^&]+)", "g");
            var matcher = pattern.exec(url);
            var items = "";
            if (null !== matcher) {
                try {
                    items = decodeURIComponent(decodeURIComponent(matcher[1]));
                } catch(e) {
                    try {
                        items = decodeURIComponent(matcher[1]);
                    } catch(e) {
                        items = matcher[1];
                    }
                }
            }
            if (items) {
                items = items.indexOf("#") > 0 ? items.substr(0, items.indexOf("#")) : items;
            }
            return items;
        }
    }
})();
var WindowsInfo =
(function () {
    var screenHeight = window.screen.height;
    var screenWidth = window.screen.width;
    var docHeight = window.innerHeight;
    var docWidth = window.innerWidth;

    return {
        screenHeight:screenHeight,
        screenWidth:screenWidth,
        docHeight:docHeight,
        docWidth:docWidth
    };
})(window);



ListPageManager.Popup = (function(layer){
    return {
        confirm:function(message,option,confirmFunc){
            option = option || {icon:3,title:'提示'};
            layer.confirm(message,option,function(idx){
                confirmFunc?confirmFunc.call():void(0);
                layer.close(idx);
            });
        },
        popDlg:function(){

        },
        popPage:function(pageUrl,title,callback){
            var title = title || "信息";
            //iframe层-父子操作
            layer.open({
                type: 2,
                title:title,
                area: ['700px', '600px'],
                fixed: false, //不固定
                maxmin: true,
                content: pageUrl,
                end:function(){
                    if(parent.succflg){
                        if(callback){
                            callback.call();
                        }
                    }
                }
            });
        },
        popFullPage:function(pageUrl,title,callback){
            var title = title || "信息";

            //iframe层-父子操作
            var idx = layer.open({
                type: 2,
                title:title,
                area: [WindowsInfo.docWidth + "px", WindowsInfo.docHeight + "px"],
                fixed: false, //不固定
                maxmin: true,
                content: pageUrl,
                end:function(){
                    if(parent.succflg){
                        if(callback){
                            callback.call();
                        }
                    }
                }
            });
            layer.full(idx);
        },
        msg:function(content,option,callback){
            option = option || {};
            layer.msg(content,option,function(){
                callback?callback.call():void(0);
            });
        },
        loading:function () {
            return layer.load(1, {
                shade: [0.1,'#fff'] //0.1透明度的白色背景
            });
        },
        close:function (idx) {
            layer.close(idx);
        }
    };
})(layer);